# encoding: utf-8
"""

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lei.chang on '11/04/2025'
    comment: 视听会议逻辑
"""
from project.middleware.qcos_util import QCOSUtil
from project.model.audio_video import Room, RoomRecording
from project.middleware.zego import Zego


class AudioService:
    """
    """
    @staticmethod
    def create_room(room_name):
        """ 创建房间
        :param room_name:
        :return:
        """
        # 创建房间
        room = Room.add(name=room_name)
        # 加入房间
        room = Room.join(room_code=room.code)

        return room

    @staticmethod
    def start_recording(room_code):
        """
        :param room_code:
        :return:
        """
        room = Room.query_one(code=room_code)
        if not room:
            raise Exception('房间不存在')

        # 开启录音
        task_id = Zego.start_recording(room_id=str(room_code))
        room.recording_id = task_id
        room.commit()

        RoomRecording.add(room_code=room.code, recording_id=task_id)

        return task_id

    @staticmethod
    def stop_recording(room_code):
        """ 停止录制
        :param room_code:
        :return:
        """
        room = Room.query_one(code=room_code)
        if not room:
            raise Exception('房间不存在')

        # 开启录音
        Zego.stop_recording(task_id=room.recording_id)

    @staticmethod
    def get_recording_files(room_code):
        """ 取得房间的录制文件列表
        :param room_code:
        :return:
        """
        ret_data = []

        records = RoomRecording.query(room_code=int(room_code))
        if not records:
            return ret_data

        recording_ids = set([v['recording_id'] for v in records])
        for recording_id in recording_ids:
            files = QCOSUtil.get_files(prefix=recording_id)
            ret_data.extend(files)

        ret_data.sort(key=lambda x: x['last_time'], reverse=True)

        return ret_data


if __name__ == "__main__":
    """
    """
    result = AudioService.get_recording_files(12345)
    print(len(result))

    print(result)
